package org.convallaria.framework.security.core;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.convallaria.framework.security.config.SecurityProperties;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

/**
 * JWT Token 提供者
 * 负责token的生成、解析、验证等操作
 * 
 * @author convallaria
 * @since 1.0.0
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class JwtTokenProvider {

    private final SecurityProperties securityProperties;

    /**
     * 生成JWT Token
     * 
     * @param securityUser 安全用户信息
     * @return JWT token
     */
    public String createToken(SecurityUser securityUser) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", securityUser.getUserId());
        claims.put("username", securityUser.getUsername());
        claims.put("tenantId", securityUser.getTenantId());
        claims.put("deptId", securityUser.getDeptId());
        claims.put("roles", securityUser.getRoles());
        claims.put("permissions", securityUser.getPermissions());
        
        Date now = new Date();
        Date expireDate = new Date(now.getTime() + securityProperties.getJwt().getExpireMinutes() * 60 * 1000L);
        
        return Jwts.builder()
                .claims(claims)
                .subject(securityUser.getUsername())
                .issuedAt(now)
                .expiration(expireDate)
                .signWith(getSecretKey(), Jwts.SIG.HS512)
                .compact();
    }

    /**
     * 解析JWT Token
     * 
     * @param token JWT token
     * @return 解析后的Claims
     */
    public Claims parseToken(String token) {
        try {
            return Jwts.parser()
                    .verifyWith(getSecretKey())
                    .build()
                    .parseSignedClaims(token)
                    .getPayload();
        } catch (ExpiredJwtException e) {
            log.warn("JWT token已过期: {}", e.getMessage());
            throw e;
        } catch (JwtException e) {
            log.error("JWT token解析失败: {}", e.getMessage());
            throw e;
        }
    }

    /**
     * 验证JWT Token
     * 
     * @param token JWT token
     * @return 是否有效
     */
    public boolean validateToken(String token) {
        try {
            Jwts.parser()
                    .verifyWith(getSecretKey())
                    .build()
                    .parseSignedClaims(token);
            return true;
        } catch (JwtException | IllegalArgumentException e) {
            log.error("JWT token验证失败: {}", e.getMessage());
            return false;
        }
    }

    /**
     * 从Claims中构建SecurityUser
     * 
     * @param claims JWT claims
     * @return SecurityUser
     */
    @SuppressWarnings("unchecked")
    public SecurityUser buildSecurityUser(Claims claims) {
        // 安全地转换roles和permissions，处理ArrayList和Set两种情况
        Set<String> roles = convertToSet(claims.get("roles"));
        Set<String> permissions = convertToSet(claims.get("permissions"));
        
        return SecurityUser.builder()
                .userId(claims.get("userId", Long.class))
                .username(claims.getSubject())
                .tenantId(claims.get("tenantId", Long.class))
                .deptId(claims.get("deptId", Long.class))
                .roles(roles)
                .permissions(permissions)
                .status(0)
                .build();
    }
    
    /**
     * 安全地将Object转换为Set<String>
     * 处理ArrayList和Set两种情况
     */
    @SuppressWarnings("unchecked")
    private Set<String> convertToSet(Object obj) {
        if (obj == null) {
            return new HashSet<>();
        }
        
        if (obj instanceof Set) {
            return (Set<String>) obj;
        }
        
        if (obj instanceof List) {
            return new HashSet<>((List<String>) obj);
        }
        
        // 如果是其他类型，尝试转换为字符串集合
        if (obj instanceof Collection) {
            return ((Collection<?>) obj).stream()
                    .map(Object::toString)
                    .collect(Collectors.toSet());
        }
        
        // 单个值的情况
        return Set.of(obj.toString());
    }

    /**
     * 获取Token剩余有效时间（秒）
     * 
     * @param token JWT token
     * @return 剩余有效时间
     */
    public long getTokenExpireTime(String token) {
        Claims claims = parseToken(token);
        Date expiration = claims.getExpiration();
        return (expiration.getTime() - System.currentTimeMillis()) / 1000;
    }

    /**
     * 刷新Token
     * 
     * @param token 旧token
     * @return 新token
     */
    public String refreshToken(String token) {
        Claims claims = parseToken(token);
        SecurityUser securityUser = buildSecurityUser(claims);
        return createToken(securityUser);
    }

    /**
     * 获取密钥
     */
    private SecretKey getSecretKey() {
        byte[] keyBytes = securityProperties.getJwt().getSecret().getBytes(StandardCharsets.UTF_8);
        return Keys.hmacShaKeyFor(keyBytes);
    }
}
